<template>
	<view class="im-wrapper-box"
		:style="{ 'background-image': `url(${gameChat.backgroundType != 'video' ? gameChat.background : ''})` }">
		<u-navbar :title="loadingText" :avatar="gameChat.face2" :name="gameChat.name2" back-icon-color="#fff"
			title-color="#ffffff" :title-size="30" :is-back="true" background="transparent">
		</u-navbar>
		<view class="video-review" v-if="videoSource&&showVideo">
			<AiVideo class="review-video" ref="previewVideo" :autoplay="true" :storyId="curStoryDetail.storyId"
				:seekTime="curStoryDetail.seekTime" :storyUrl="curStoryDetail.storyUrl"
				:storySet="curStoryDetail.storySet" :preStoryId="curStoryDetail.preStoryId"
				:nextStoryId="curStoryDetail.nextStoryId" :actions="curStoryDetail.actions"
				:actionsFlag="curStoryDetail.actionsFlag" :gameId="goodsId" :openQTE="curStoryDetail.openQTE"
				:QTEtype="curStoryDetail.QTEtype" :QTESec="curStoryDetail.QTESec" :selfLoop="curStoryDetail.selfLoop"
				:loopSec="curStoryDetail.loopSec" :isMultiVideo="curStoryDetail.isMultiVideo"
				:sectionsConfig="curStoryDetail.sectionsConfig" :showRecord="curStoryDetail.showRecord"
				:checkoutEvent="curStoryDetail.checkoutEvent" :currentInit="true" @selsetAction="selsetAction"
				:controls="true" :height="'100vh'">
			</AiVideo>
			<image class="closeVideo" src="../../static/img/close.png" mode="" @click="handleCloseVideo"></image>
		</view>
		<!-- 	<view class="top-info">
			<view class="avatar">
				<u-avatar :src="gameChat.face2" img-mode="aspectFill"> </u-avatar>
			</view>
		</view> -->
		<!-- 聊天内容区域 -->
		<scroll-view ref="scrollView" scroll-y refresher-enabled :refresher-triggered="mfreshing"
			:refresher-threshold="100" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
			@refresherrestore="onRestore" @refresherabort="onAbort" class="position-fixed scroll-view-box"
			:style="chatBodyBottom" :show-scrollbar="false" :scroll-into-view="scrollIntoView"
			:scroll-with-animation="true">
			<!-- 消息 -->
			<view :id="'chatItem_' + index" :ref="'chatItem_' + index" class="flex-column-start msgList-box"
				v-for="(item, index) in msgList" :key="index">
				<view v-if="compareTime(index, item.createTime)" class="flex-row-start column-time compareTime">
					<view class="flex-row-start date-text" v-text="timeDetia(item.createTime)"> </view>
				</view>
				<!-- 用户 -->
				<view v-if="item.my" class="flex justify-end padding-right one-show">
					<view class="flex justify-end align-center" style="width: 540rpx">
						<view class="flex justify-end align-center padding-chat bg-user-orang"
							style="border-radius: 24rpx 4rpx 24rpx 24rpx">
							<text v-if="item.messageType === 'MESSAGE'"
								style="word-break: break-all">{{ item.text }}</text>
						</view>
					</view>
					<!-- <view style="margin-left: 12rpx">
						<u-avatar :src="gameChat.face1" img-mode="aspectFill"></u-avatar>
					</view> -->
				</view>
				<!-- AI角色 -->
				<view v-else class="flex margin-left one-show">
					<!-- 	<view class="chat-img flex-row-center">
						<u-avatar :src="gameChat.face2" img-mode="aspectFill"> </u-avatar>
					</view> -->
					<view class="flex" style="width: 500rpx;">
						<view>
							<view class="margin-left padding-chat flex-column-start "
								style="border-radius: 4rpx 24rpx 24rpx 24rpx; margin-left: 12rpx;position: relative;"
								:class="{'bg-to-color':(item.messageType!='EMO'&&item.messageType!='SYSTEM'),'system-message-style':item.messageType=='SYSTEM'}">
								<text v-if="item.messageType === 'MESSAGE'"
									style="word-break: break-all">{{ item.text }}</text>
								<view v-if="item.messageType === 'SYSTEM'" style="word-break: break-all"
									class="text-title-style">祝贺你！
								</view>

								<text v-if="item.messageType === 'SYSTEM'" style="word-break: break-all"
									class="text-style">{{ item.text }}
									<text class="clickLook" @click="handlePutDownPhone">点击查看</text>
								</text>
								<!-- <view class="clickLook" v-if="item.messageType === 'SYSTEM'"
									@click="handlePutDownPhone">点击查看</view> -->
								<view v-if="item.messageType === 'VOICE'" class="voice-box">
									<!-- <myAudio :item="item" :index="index"></myAudio> -->
								</view>
								<view class="red-ponit" v-if="item.messageType=='VOICE'"></view>
								<view @click="previewImages(item)" v-if="item.messageType === 'PICTURE'"
									style="position: relative;">
									<image :src="item.text" style="object-fit: cover;" class="PICTURE-class" />

								</view>
								<view @click="previewImages(item)" v-if="item.messageType === 'EMO'">
									<image :src="item.text" style="object-fit: cover;" class="EMO-class" />
								</view>
								<view @click="previewVideo(item)" v-if="item.messageType==='VIDEO'" class="VIDEO-class"
									style="position: relative;">
									<video :src="item.text" style="object-fit: cover;width: 100%;height: 100%;"
										:controls="false"></video>
									<image class="play-icon" src="../../static/img/play-btn.png" mode=""></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- loading是显示 -->
			<!-- 			<view v-if="msgLoad" class="msgLoad-box margin-left">
				<view class="avatar-box">
					<u-avatar :src="gameChat.face2"></u-avatar>
				</view>
				<view class="mgs-box">
					<view class="msgLoading"> 正在输入中... </view>
				</view>
			</view> -->
		</scroll-view>

		<!-- 输入栏 -->
		<!-- 		<aiInput ref="aiInput" :isShowMagicIcon="false" :buttonList="buttonList" @sendMessage="sendMessage"
			@pageToBottom="pageToBottom" @openGiftPop="openGiftPop"> </aiInput> -->

		<!-- 底部背景色 -->
		<view class="bottom-bg"> </view>
		<view class="masker" v-if="showPutDownBtn">
			<button class="putDownBtn" @click="handlePutDownPhone">放下手机</button>
		</view>
		<image class="posPutDown"
			src="https://cdn.osisx.com/e7370194a3d3a7baa0013dc707667726/image/6e825883470747e084aafc995a631756.png"
			@click="handlePutDownPhone1"></image>


	</view>
</template>

<script>
	// #ifdef APP-PLUS-NVUE
	const dom = weex.requireModule('dom');
	// #endif

	import {
		getTalkMessage,
		reloadChat
	} from '@/api/im.js';

	import {
		getChatDetailApi,
		sendChatMessageApi
	} from '@/api/zhongyi.js';

	import {
		beautifyTime,
		timeDetia
	} from '@/utils/filters.js';

	// import myAudio from '@/components/myAudio/index.vue';

	import AiVideo from "@/components/ai-video/index.vue"

	// import aiInput from '@/components/ai-input/index.vue';

	import {
		mapMutations,
		mapState,
		mapGetters
	} from 'vuex';

	export default {
		components: {
			// myAudio,
			// aiInput,
			AiVideo
		},
		props: {
			gameId: {
				type: [Number, String],
				default: '',
			},
			storyId: {
				type: [Number, String],
				default: '',
			},
			// chatId: {
			// 	type: [Number, String],
			// 	default: '',
			// },
		},
		watch: {
			// chatId: {
			// 	deep: true,
			// 	immediate: true,
			// 	handler(v) {
			// 		console.log(v, 'chatId-----------');
			// 	},
			// },
			curStoryType: {
				deep: true,
				immediate: true,
				handler(v) {
					console.log(v, 'curStoryType');
					if (v === 'agentChat') {
						this.upDateChatList()
					}
				},
			}
		},
		data() {
			return {
				showVideo: false,
				videoSource: "",
				showPutDownBtn: false,
				bottom: 248,
				mfreshing: false,
				scrollIntoView: '',
				navBarHeight: 0,
				chatId: "",
				params: {
					//搜索条件
					chatId: '',
					pageSize: 10,
					pageNumber: 1,
				},
				msgList: [],
				lastScrollTop: 0, // 用于存储上一次的滚动位置
				msgLoad: false,
				lastTime: 0,
				canPlay: false,
				gameChat: {},
				buttonList: [{
					name: '重启',
					url: '../../static/img/return-icon.svg',
				}, ],
			};
		},
		computed: {
			...mapState(['vKeyboardHeight', 'curStoryType']),
			...mapGetters(['globalGameCtx']),
			// 聊天区域bottom
			chatBodyBottom() {
				let curB = this.vKeyboardHeight > 0 ? -uni.upx2px(48) : 0;
				console.log("发生修改",
					`bottom:${uni.upx2px(this.bottom) + curB + this.vKeyboardHeight}px;top:${this.navBarHeight}px;`);
				return `bottom:${uni.upx2px(this.bottom) + curB + this.vKeyboardHeight}px;top:${this.navBarHeight}px;`;
			},
			loadingText() {
				if (this.msgLoad) {
					return "正在输入中..."
				} else {
					return ""
				}
			},
			curStoryDetail() {
				return {
					storyUrl: this.videoSource,
					storyId: "previewVideo"
				}
			}
		},
		created() {
			var statusBarHeight = 0;
			// #ifdef APP-PLUS-NVUE
			statusBarHeight = plus.navigator.getStatusbarHeight();
			// #endif

			this.navBarHeight = statusBarHeight + uni.upx2px(170);
		},
		mounted() {
			this.canPlay = true;

		},
		methods: {
			...mapMutations(['changeKeyBordHeight']),
			handleCloseVideo() {
				// console.log("点击关闭视频");
				// this.showVideo = false

				this.$emit("showInput", (back) => {
					// console.log("返回的是", back);
					// 测试地方
					this.videoSource =
						""
					this.showVideo = false

				})
			},
			selsetAction(action, callback) {
				if (action.event === 'seekEvent') {
					// 跳转线索
					this.$refs.previewVideo.seekEvent(action.seekEventTime)
					callback(false);
				}
			},
			handlePutDownPhone1() {
				this.msgLoad = false
				let preStoryId = this.globalGameCtx.preStoryId
				if (preStoryId) {
					this.$emit("playTargetStory", [
						preStoryId,
						(flag) => {
							if (flag) {
								// 隐藏掉失败页面
								this.showPutDownBtn = false
							}
						},
					]);
				}
			},
			handlePutDownPhone() {
				console.log("点击查看了");
				this.msgLoad = false
				let nextStoryId = this.globalGameCtx.nextStoryId
				if (nextStoryId) {
					this.$emit("playTargetStory", [
						nextStoryId,
						(flag) => {
							if (flag) {
								// 隐藏掉失败页面

								this.showPutDownBtn = false
							}
						},
					]);
				}

			},
			showPutDownPhone() {
				this.showPutDownBtn = true
			},
			upDateChatList(type) {
				if (type == 'reload') {
					this.msgList = []
					this.params.pageNumber = 1
					this.params.pageSize = 10
					this.msgLoad = false
					this.$emit("controlInput", false)

				}
				this.chatId = this.globalGameCtx.gameChat.id
				// this.getChatDetail();
				this.gameChat = this.globalGameCtx.gameChat;
				this.getTalkMessageMethod();

			},
			changeInputType(type) {
				if (type == 'text') {
					this.bottom = 148
					this.pageToBottom()
				} else if (type == 'voice') {
					this.bottom = 348
					this.pageToBottom()
				}
			},
			pushUserMessage(message) {
				this.msgList.push({
					text: message,
					my: true,
					messageType: 'MESSAGE',
				});

				this.pageToBottom();
				this.msgLoad = true;
				this.$emit("controlInput", true)
			},
			previewVideo(item) {
				let filePaths = "";
				let msgDataArr = this.msgList.filter((msg) => {
					return msg.id === item.id;
				});
				if (msgDataArr.length) {
					filePath = msgDataArr[0].text
					this.$emit("hideInput", (back) => {
						// console.log("返回的是", back);
						// 测试地方
						this.videoSource = filePath
						this.showVideo = true

					})

				}



			},
			previewImages(item) {


				let targetIndex = this.msgList.findIndex((msg) => {
					return msg.id === item.id;
				});
				let filePaths = [];
				this.msgList.forEach((item) => {
					if (item.messageType == 'PICTURE') {
						filePaths.push(item.text);
					}
				});
				// 预览图片
				uni.previewImage({
					current: targetIndex,
					urls: filePaths,
					longPressActions: {
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						},
					},
				});
			},
			// 此项是否可播放
			canChangeCurrent(callback) {
				callback(this.canPlay);
			},
			stopStory(callback) {
				callback(true);
			},
			startPlay(callback) {
				callback(true);
			},
			openGiftPop() {
				this.$emit('openGiftPop');
			},
			reset() {
				let params = {
					gameId: this.gameId,
					storyId: this.storyId,
					chatId: this.chatId,
				};
				reloadChat(params).then((res) => {
					if (res.data.success) {
						this.getTalkMessageMethod();
					}
				});
			},
			onPulling(e) {},
			onRefresh() {
				if (this.mfreshing) return;
				this.getTalkMessageMethod(false);
			},
			onRestore() {
				this.mfreshing = false; // 需要重置
			},
			onAbort() {
				console.log('onAbort');
			},
			// 回到底部
			pageToBottom() {
				// #ifdef APP-PLUS-NVUE
				let msgList = this.msgList;
				let lastIndex = msgList.length > 0 ? msgList.length - 1 : 0;
				if (msgList[lastIndex]) {
					dom.scrollToElement(msgList[lastIndex], {});
				}
				// #endif

				// #ifndef APP-NVUE
				setTimeout(() => {
					console.log("调用-lll", this.msgList.length - 1);
					let lastIndex = this.msgList.length - 1;
					this.$set(this, 'scrollIntoView', 'chatItem_' + lastIndex);
					console.log('scrollIntoView---// 回到底部');
				}, 300);
				// this.$nextTick(() => {
				// 	console.log("调用-lll", this.msgList.length - 1);
				// 	let lastIndex = this.msgList.length - 1;
				// 	this.$set(this, 'scrollIntoView', 'chatItem_' + lastIndex);
				// 	console.log('scrollIntoView---// 回到底部');
				// })
				// #endif
			},

			sendMessage(message) {
				if (!message) {
					return false;
				}
				let currentTime = new Date().getTime();
				if (this.lastTime !== 0) {
					if (currentTime - this.lastTime < 1000) {
						// this.$refs.aiInput.reset();
						this.lastTime = currentTime;
						return;
					}
				}
				this.lastTime = currentTime;

				let chatMessage = {
					gameChatId: this.gameChat.id,
					toUser: this.gameChat.agentId,
					fromUser: this.gameChat.memberId,
					gameId: this.gameId,
					storyId: this.storyId,
					messageType: 'MESSAGE',
					text: message,
				};

				this.msgList.push({
					text: message,
					my: true,
					messageType: 'MESSAGE',
				});

				this.pageToBottom();

				// this.$refs.aiInput.reset();
				this.msgLoad = true;
				this.$emit("controlInput", true)
				sendChatMessageApi(chatMessage).then((res) => {
					if (res.data.success) {
						let result = res.data.result;
						this.msgLoad = false;
						this.$emit("controlInput", false)
						this.setMessage(result);
					}
				});
			},

			/**
			 * @param {Object} result 列表数据，需要加定时器，每隔1-3秒插入一条消息
			 */
			setMessage(results) {
				// this.msgLoad = false = false;
				let resLength = results.length
				if (!resLength) {
					this.msgLoad = false
					this.$emit("controlInput", false)
					if (this.globalGameCtx.nextStoryId) {
						this.showPutDownPhone()
					}
					return
				} else {
					results = results.map((item, index) => {
						return {
							...item,
							isNew: true
						}
					})
				}
				const insertMessage = (index) => {
					if (index < results.length) {
						const result = results[index];
						this.msgList.push(result);
						this.msgLoad = false
						this.pageToBottom();

						let nextResult = results[index + 1]
						if (nextResult) {
							setTimeout(() => {
								this.msgLoad = true
							}, 200)
						}

						// 随机生成下一条消息的插入延迟时间（1-3秒） 第一句本来就不延迟
						// const delay = 1000 + Math.floor(Math.random() * 2000);
						let delay = 1000
						if (nextResult && nextResult.messageType == 'MESSAGE') { //这样子控制的是吓一跳消息的时间，而不是本条消息的时间
							let length = nextResult.text.length
							console.log("长度", nextResult, length);
							if (length < 4) {
								delay = 1000
							} else {
								let num1 = length / 4
								let num2 = length % 4
								delay = (num2 === 0) ? num1 * 1000 : (num1 + 1) * 1000
							}

						}
						// console.log("延迟时长", delay, result);

						if (index == results.length - 1) {
							this.msgLoad = false;
							this.$emit("controlInput", false)
							if (this.globalGameCtx.nextStoryId) {
								this.showPutDownPhone()
							}
						}



						setTimeout(() => insertMessage(index + 1), delay);
					}
				};

				// 开始插入消息
				insertMessage(0);
			},

			beautifyTime,
			timeDetia,

			getChatDetail() {

				let params = {
					...this.params,
					chatId: this.chatId,
				};
				console.log("当前的参数", params);
				getChatDetailApi(params).then((res) => {
					if (res.data.success) {
						let gameChat = res.data.result;
						this.gameChat = gameChat;
						this.getTalkMessageMethod();
					}
				});
			},

			// 根据talkID获取聊天记录
			getTalkMessageMethod(toBottom = true) {
				this.mfreshing = true;
				let params = {
					...this.params,
					chatId: this.chatId,
				};
				getTalkMessage(params).then((res) => {
					console.log("刷新成功", this.mfreshing);
					this.mfreshing = false;
					let result = res.data.result;


					if (res.data.success && result && result.length > 0) {
						this.params.pageNumber = this.params.pageNumber + 1;

						let targets = result.map((item) => {
							if (item.fromUser === this.gameChat.memberId) {
								item.my = true;
							}
							return item;
						});

						// targets.push({
						// 	my: false,
						// 	messageType: "VOICE",
						// 	msgLength: 6
						// 	// text: "https://cdn.osisx.com/3b7a9d7db5ee1ad249b012a1e747bed3/audio/6583a0a9f6cd4515ad489d0478b9bedd.MP3"
						// })

						this.msgList.unshift(...targets);
						console.log("列表是", this.msgList);

						setTimeout(() => {
							if (toBottom) {
								this.pageToBottom();
							}
						}, 10);
					}
				});
			},

			// 处理消息时间是否显示
			compareTime(index, datetime) {
				let flag = false;
				let time = datetime || null;
				let nextTime = this.msgList[index + 1] ? this.msgList[index + 1].createTime : null;
				let curTime;

				if (time) {
					let t = time.replace(/-/g, '/');
					time = Math.floor(Date.parse(t) / 1000);
				}

				if (nextTime) {
					let n = nextTime.replace(/-/g, '/');
					nextTime = Math.floor(Date.parse(n) / 1000);
				}

				// 两条信息之间相隔大于3分钟
				if (nextTime - time > 180) {
					flag = true;
				}
				return flag;
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import './index.scss';

	.voice-box {
		position: relative;
	}

	.red-ponit {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		right: -44rpx;
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		background-color: rgba(255, 59, 48, 1);

	}

	.video-review {
		position: absolute;
		left: 0;
		top: 0;
		background-color: #000;
		// width: 100vw;
		// height: 100vh;
		// .review-video{
		// 	width: 100%;
		// 	height: 100%;
		// }
		z-index: 999999999;
		width: 100vw;
		height: 100vh;
		// animation: startShowVideo 1s linear
	}

	@keyframes startShowVideo {
		0% {
			width: 0%;
			height: 0%;
		}

		50% {
			width: 50%;
			height: 50%;
		}

		100% {
			width: 100%;
			height: 100%;
		}
	}

	.compareTime {
		margin-bottom: 36rpx;
		margin-top: 12rpx;
		font-weight: 400;
		font-size: 26rpx;
		color: #838383;
	}

	.masker {
		position: absolute;
		left: 0;
		top: 0;
		width: 100vw;
		height: 100vh;
		background-color: rgba(0, 0, 0, .3);
		display: flex;
		justify-content: center;
		align-items: center;
		animation: showPutDown 0.5s linear;

		.putDownBtn {}
	}

	.posPutDown {
		position: absolute;
		right: 150rpx;
		bottom: 750rpx;
		width: 50rpx;
		height: 50rpx;
		font-size: 32rpx;
		background-color: transparent;
	}


	@keyframes showPutDown {
		0% {
			opacity: 0;
		}

		100% {
			opacity: 1;
		}
	}

	.top-info {
		position: fixed;
		top: 0rpx;
		left: 0rpx;
		width: 100vw;
		height: 72rpx;
		background-color: pink;
	}

	.system-message-style {
		background-color: rgba(0, 0, 0, .4);
		border-radius: 24rpx !important;

		.text-title-style {
			color: #fff
		}

		.text-style {
			color: #928e8f;
		}

		.clickLook {
			color: #f9db80;
			font-weight: 700;
			pointer-events: fill;
		}

	}

	.closeVideo {
		background-color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		position: absolute;
		left: 40rpx;
		top: 90rpx;
		width: 50rpx;
		height: 50rpx;
		z-index: 999999999;
		border-radius: 50%;
	}
</style>